package com.vision.pdp.Activity;


import com.vision.frame.Bean.ResultObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;

@Controller
@Api(tags = "Activity")
@RequestMapping("/Activity")
public class ActivityControl {

    @Resource
    private Environment env;


    @ResponseBody
    @PostMapping(value = "/getFilePath")
    @ApiOperation(value = "获取流程图文件路径（prjCode必填）")
    public ResultObject getFilePath(HttpServletRequest request, HttpServletResponse response, @RequestBody MXGraphDTO mxGraphDTO) {
        ResultObject ResultObject = new ResultObject();
        try {

            String filePath = env.getProperty("vision.mxgraphFilePath") + "/" +mxGraphDTO.getPrjCode() + ".xml";
            File file = new File(filePath);
            if (file.exists()) {
                ResultObject.setObjOther(filePath);
            }

        } catch (Exception e) {
            ResultObject.onSetErrorMsg(e);
        }
        return ResultObject;
    }

    @ResponseBody
    @PostMapping(value = "/getFileXML")
    @ApiOperation(value = "获取流程图文件内容（prjCode必填）")
    public void getFileXML(HttpServletRequest request, HttpServletResponse response, @RequestBody MXGraphDTO mxGraphDTO) {
        try{

            String filePath = env.getProperty("vision.mxgraphFilePath") + "/" +mxGraphDTO.getPrjCode() + ".xml";
            System.out.println("文件路径："+filePath);
            File file = new File(filePath);
            if (file.exists() ) {

                try(FileInputStream input = new FileInputStream(file)){
                    byte[] data;
                    data = new byte[input.available()];
                    input.read(data);
                    response.getOutputStream().write(data);

                } catch (Exception e) {
                    throw new Exception(e);
                }


            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    @ResponseBody
    @PostMapping(value = "/saveXML")
    @ApiOperation(value = "保存流程图文件内容（prjCode、xmlBlob必填）")
    public ResultObject saveXML(HttpServletRequest request, HttpServletResponse response,  @RequestBody MXGraphDTO mxGraphDTO) {
        ResultObject resultObject = new ResultObject();
        try
        {
            System.out.println(mxGraphDTO);
            String blob = mxGraphDTO.getXmlBlob();
            String filePath = env.getProperty("vision.mxgraphFilePath") + "/" +mxGraphDTO.getPrjCode() + ".xml";
            // 删除对应文件
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                file.delete();
            }
            // 写入新文件
            file.createNewFile();
            try(FileOutputStream o = new FileOutputStream(file))
            {
                o.write(blob.getBytes(StandardCharsets.UTF_8));
            }

        }
        catch (Exception e)
        {
            resultObject.onSetErrorMsg(e);
        }

        return resultObject;
    }


    @ResponseBody
    @PostMapping(value = "/getActivityList")
    @ApiOperation(value = "（假数据）获取活动列表（prjCode必填）", notes = "ptrCode不传查所有活动，否则查对应ptr下的活动，其他参数不用填空")
    public ResultObject getActivityList(HttpServletRequest request, HttpServletResponse response,  @RequestBody ActivityDTO activityDTO) {
        ResultObject resultObject = new ResultObject();

        String jsonString ;
        try
        {
            // 获取on等
            String prtCode = activityDTO.getPtrCode();
            System.out.println("通过数据库获取该项目的活动列表");
            String filePath = env.getProperty("vision.mxgraphFilePath") + "/" + activityDTO.getPrjCode() + ".json";
            File file = new File(filePath);
            ClassPathResource resource = new ClassPathResource("ActivityList.json");
            // 如果数据不存在拷贝一份
            if (!file.exists()) {
                file.createNewFile();
                try(OutputStream outputStream = new FileOutputStream(file);
                    InputStream inputStream = resource.getInputStream())
                {
                    byte[] data = new byte[1024];
                    int temp = 0;
                    while ((temp = inputStream.read(data)) != -1){
                        outputStream.write(data,0,temp);
                    }
                }
            }
            ArrayList<HashMap<String, Object>> result = new ArrayList<>();
            try(InputStream inputStream = new FileInputStream(filePath))
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream , "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                jsonString = sb.toString();
                JSONObject jsonObject = new JSONObject(jsonString);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for(int i = 0; i < jsonArray.length(); i++){
                    JSONObject item = jsonArray.getJSONObject(i);
                    String ptr = item.getString("PTRCode");
                    HashMap<String, Object> map = new HashMap<>();
                    if(StringUtils.isBlank(prtCode))
                    {
                        map.put("UUID", item.getString("UUID"));
                        map.put("Code", item.getString("Code"));
                        map.put("Name", item.getString("Name"));
                        map.put("PTRCode", item.getString("PTRCode"));
                        map.put("planBegDate", item.getString("planBegDate"));
                        map.put("planEndDate", item.getString("planEndDate"));
                        result.add(map);
                    }
                    else if(StringUtils.isNotBlank(prtCode) && ptr.indexOf(";"+prtCode+";")> -1){
                        map.put("UUID", item.getString("UUID"));
                        map.put("Code", item.getString("Code"));
                        map.put("Name", item.getString("Name"));
                        map.put("PTRCode", item.getString("PTRCode"));
                        map.put("planBegDate", item.getString("planBegDate"));
                        map.put("planEndDate", item.getString("planEndDate"));
                        result.add(map);
                    }
                }
            }

            resultObject.setRows(result);
        }
        catch (Exception e)
        {
            resultObject.onSetErrorMsg(e);
        }

        return resultObject;
    }

    @ResponseBody
    @PostMapping(value = "/updateActivity")
    @ApiOperation(value = "更新活动（prjCode，UUID必填）", notes = "根据UUID更新活动，更新内容为计划开始时间和计划结束时间以及活动名称")
    public ResultObject updateActivity(HttpServletRequest request, HttpServletResponse response,  @RequestBody ActivityDTO activityDTO) {
        ResultObject resultObject = new ResultObject();

        String jsonString ;
        try
        {
            // 获取活动基本信息
            String UUID = activityDTO.getUuid();
            String name = activityDTO.getName();
            String planBegDate = activityDTO.getPlanBegDate();
            String planEndDate = activityDTO.getPlanEndDate();
            JSONObject jsonObject = new JSONObject();

            System.out.println("通过数据库更新活动");
            String filePath = env.getProperty("vision.mxgraphFilePath") + "/" + activityDTO.getPrjCode() + ".json";
            try(InputStream inputStream = new FileInputStream(filePath))
            {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream , "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                jsonString = sb.toString();
                jsonObject = new JSONObject(jsonString);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for(int i = 0; i < jsonArray.length(); i++){
                    JSONObject item = jsonArray.getJSONObject(i);
                    if(UUID.equalsIgnoreCase(item.getString("UUID"))) {
                        item.put("Name", name);
                        item.put("planBegDate", planBegDate);
                        item.put("planEndDate", planEndDate);
                    }
                }
            }
            try (FileWriter file = new FileWriter(filePath)) {
                file.write(jsonObject.toString());
            }

        }
        catch (Exception e)
        {
            resultObject.onSetErrorMsg(e);
        }

        return resultObject;
    }



}
